//
//  SJStatusCell.swift
//  SJWeiboSwift
//
//  Created by app;e on 15/10/6.
//  Copyright © 2015年 world. All rights reserved.
//

import UIKit
import SDWebImage

/// 原创微博
let SJStatusNormalCellReuseIdentifier = "SJStatusNormalCellReuseIdentifier"
/// 转发微博
let SJStatusForwardCellReuseIdentifier = "SJStatusForwardCellReuseIdentifier"

private let SJStatusPictureCellReuseIdentifier = "SJStatusPictureCellReuseIdentifier"

protocol SJStatusCellDelegate:NSObjectProtocol{
    func statusCellDidSelectedPhoto(cell:SJStatusCell,index:Int)
}

class SJStatusCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate {
    ///图片的顶部约束
    private var topConstraint: NSLayoutConstraint?
    /// 图片的宽度约束
    private var widthConstraint:NSLayoutConstraint?
    /// 图片的高度约束
    private var heightConstraint:NSLayoutConstraint?
    
    
    ///代理属性
    weak var photoDelegate:SJStatusCellDelegate?
    /// 转发微博文字
    var forwardLabel: UILabel?
    
    //微博模型属性
    var status: SJStatus?{
        didSet{
            //设置转发微博内容
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "" )+":" +  (status?.retweeted_status?.text ?? "")
            
            /// 设置头像
            iconImageView.sd_setImageWithURL(status?.user?.profileURL)
            /// 设置认证图片
            memberImageView.image = status?.user?.verrifiedImage
            /// 设置会员图片
            vipImageView.image = status?.user?.vipImage
            
            nameLabel.text = status?.user?.name
            timeLable.text = "刚刚"
            sourceLabel.text = status?.source
            contentLabel.text = status?.text
            //获取图片size
            let result = calculatorPictureViewSize(status!)
            widthConstraint?.constant = result.viewSize.width
            heightConstraint?.constant = result.viewSize.height
            topConstraint?.constant = result.viewSize.width == 0 ? 0:12
            layout.itemSize = result.itemSize
            //刷新图片视图
            pictureView.reloadData()
        }
    }
    //根据微博模型 返回一个 重用标识
    class func cellReuseIdentifier(status: SJStatus)->String{
        return status.retweeted_status != nil ? SJStatusForwardCellReuseIdentifier :SJStatusNormalCellReuseIdentifier
    }
    
    /**
    根据模型计算行高
    */
    func rowHeight(status:SJStatus)->CGFloat{
        //给status赋值,就会触发status的didset方法,进行布局
        self.status = status
        layoutIfNeeded()
        
        //返回页脚的最大Y值
        return CGRectGetMaxY(footerView.frame)
    }
    /**
    记录配图的约束
    
    - parameter cons: 配图的约束数组
    */
    func recordPictureViewCons(cons:[NSLayoutConstraint]){
        widthConstraint = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightConstraint = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        topConstraint = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
        
    }
    
    /**
    根据微博模型计算图片的大小
    0.没有图片,返回zero
    1.单图    返回图片的实际尺寸
    2.多图    图片大小固定
    4张     : 按照2*2显示
    多图其他 : 按照3*3显示
    */
    func calculatorPictureViewSize(stauts:SJStatus)->(viewSize:CGSize,itemSize:CGSize){
        
        //多张图片的大小
        let itemSize = CGSize(width: 90, height: 90)
        //间距
        let margin:CGFloat = 10
        
        //1.获取图片数量
        let imageCount = status?.picURLs?.count ?? 0
        
        //2.没有图片
        if imageCount == 0 {
            return (CGSizeZero,itemSize)
        }
        //3.一张图片
        if imageCount == 1 {
            //从缓存中 拿到 并创建 image
            //key 就是 url的完整字符串 sdwebImage缓存图片名是图片url字符串进行 md5
            let key = status!.picURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return image == nil ? (CGSizeZero,itemSize) : (image.size,image.size)
        }
        
        //4.4张图片
        if imageCount == 4 {
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w),itemSize)
        }
        //5.其他
        //2,3   1行
        //5.6   2行
        //7.8.9 3行
        //每列的行数
        let rowCount = 3
        //多少行
        let row = (imageCount-1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        return (CGSize(width: w, height: h),itemSize)
    }
    
    /**
    准备配图视图
    */
    private func preparePictureView(){
        //1.设置背景颜色
        pictureView.backgroundColor = UIColor.lightGrayColor()
        //2.数据源与代理
        pictureView.dataSource = self
        pictureView.delegate = self
        //3.注册可重用cell
        pictureView.registerClass(SJStatusPictureCell.self, forCellWithReuseIdentifier: SJStatusPictureCellReuseIdentifier)
        //4.设置layout
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        
    }
    
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        //屏幕宽度
        let screenW = UIScreen.mainScreen().bounds.width
        //cell顶部视图页眉
        let topView = UIView()
        addSubview(topView)
        topView.backgroundColor = UIColor(white: 0.6, alpha: 1)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenW, height: 8))
        //添加子空间
        addSubview(iconImageView)
        addSubview(nameLabel)
        addSubview(vipImageView)
        addSubview(memberImageView)
        addSubview(timeLable)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - CGFloat(12)
        addSubview(pictureView)
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        //准备配图
        preparePictureView()
        
        //设置子控件约束
        iconImageView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 20))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconImageView, size: nil, offset: CGPoint(x: 12, y: 0))
        vipImageView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: CGSize(width: 14, height: 14), offset: CGPoint(x: 12, y: 0))
        memberImageView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconImageView, size: CGSize(width: 17, height: 17), offset: CGPoint(x: 8, y: 8))
        timeLable.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconImageView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLable, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconImageView, size: nil, offset: CGPoint(x: 0, y: 12))
        
        //        pictureView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil, offset: CGPoint(x: -8, y: -8))
        
        //页脚
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenW, height: 44), offset: CGPoint(x: -12, y: 12))
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// MARK: - collectionView的数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.picURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SJStatusPictureCellReuseIdentifier, forIndexPath: indexPath) as! SJStatusPictureCell
        cell.imageURL = status!.picURLs![indexPath.item]
        return cell
    }
    
    ///计数cell中大图对应全屏之后的frame
    func fullScreenFrameOfPhotoIndex(photoIndex:Int) -> CGRect{
        let urlString = status?.picURLs![photoIndex].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
        
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        let w = screenSize.width
        let h = scale * w
        var y: CGFloat = 0
        if screenSize.height > h{
            y = (screenSize.height - h) * 0.5
        }
        return CGRectMake(0, y, w, h)

    }
    
    
    ///计算cell 转换成 屏幕的frame
    func screenFrameOfPhotoIndex(photoIndex:Int) -> CGRect{
        let indexPath = NSIndexPath(forItem: photoIndex, inSection: 0)
          let cell = pictureView.cellForItemAtIndexPath(indexPath) as! SJStatusPictureCell
        //将用户点击的cell的坐标 转换成屏幕的坐标
        //        let screenFrame = pictureView.convertRect(cell.frame, toView: UIApplication.sharedApplication().keyWindow)
        // func convertRect(rect: CGRect, toCoordinateSpace coordinateSpace: UICoordinateSpace) -> CGRect 将rect转换到coordinateSpace坐标系
        //这个参数必须是遵守UICoordinateSpace协议的对象, 而UIView是遵守了UICoordinateSpace协议的
        let screenFrame = pictureView.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return screenFrame
    }
    
    /// MARK: - collectionView的代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //        print(status?.largePicURLs![indexPath.item])
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! SJStatusPictureCell
        
        let url = status?.largePicURLs![indexPath.item]
//        let screenF = screenFrameOfPhotoIndex(indexPath.item)
//        let fullF = fullScreenFrameOfPhotoIndex(indexPath.item)
//        let view = UIView(frame: fullF)
//        view.backgroundColor = UIColor.redColor()
//        UIApplication.sharedApplication().keyWindow!.addSubview(view)
       
        
        
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (current, totol) -> Void in
            //                print([NSThread .currentThread()])
            //回到主线程更新UI
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                cell.iconView.progress = CGFloat(current) / CGFloat(totol)
            })

            }) { (_ , error , _ , _ , _ ) -> Void in
                if error == nil {
                    //缓存完成 在调转 到图片浏览器
                    self.photoDelegate?.statusCellDidSelectedPhoto(self, index: indexPath.item)
                }

        }
        
    }
    
    
    /// MARK: - 懒加载
    //头像
    lazy var iconImageView: UIImageView = UIImageView()
    //姓名
    lazy var nameLabel:UILabel = UILabel(color: UIColor.darkGrayColor(), textSize: UIFont.systemFontOfSize(14), mutableLines: false)
    //会员图标
    lazy var vipImageView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
    //认证图标
    lazy var memberImageView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
    
    //时间
    lazy var timeLable:UILabel = UILabel(color: UIColor.orangeColor(), textSize: UIFont.systemFontOfSize(10), mutableLines: false)
    //来源
    lazy var sourceLabel:UILabel = UILabel(color: UIColor.grayColor(), textSize: UIFont.systemFontOfSize(10), mutableLines: false)
    // 正文text
    lazy var contentLabel:UILabel = UILabel(color: UIColor.darkGrayColor(), textSize: UIFont.systemFontOfSize(15), mutableLines: true)
    // 配图view
    lazy var layout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    // 底部页脚
    lazy var footerView:SJStatusFooterView = SJStatusFooterView()
    
}


///  pictureView(继承collectionView) 的 cell类
private class SJStatusPictureCell:UICollectionViewCell {
    /// 图像地址
    var imageURL:NSURL?{
        didSet{
            //设置图片的初始进度
            iconView.progress = 0
            
            //该方法会先从沙盒缓存中取,如果没有值再去网络加载
            iconView.sd_setImageWithURL(imageURL)
            
             gifIcon.hidden = !(imageURL?.absoluteURL.pathExtension?.lowercaseString == "gif")
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        
        //设置图片的填充模式
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        //超出frame的部分裁剪掉
        iconView.clipsToBounds = true
        
        //设置图像的frame 与collectionView 一样
        iconView.ff_Fill(self)
        
        //添加gif
        addSubview(gifIcon)
        gifIcon.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 图像
    lazy var iconView: SJImageView = SJImageView()
    // gif
    lazy var gifIcon:UIImageView = {
        let gif = UIImageView(image: UIImage(named: "timeline_image_gif"))
        gif.hidden = true
        return gif
        }()
}

/// cell的底部页脚
class SJStatusFooterView:UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        //三个按钮水平平铺
        ff_HorizontalTile([forwardBtn,commentBtn,likeBtn], insets: UIEdgeInsetsZero)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn:UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", titleSize: 12)
    lazy var commentBtn:UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", titleSize: 12)
    lazy var likeBtn:UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", titleSize: 12)
    
}
